package com.sunagy.demand.front.utils;

import com.sunagy.demand.front.enums.BuzEnum;
import com.sunagy.demand.front.exception.BuzException;
import com.sunagy.demand.front.security.SecurityUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * desc：#上下文中的用户信息
 * author：三餘無夢生
 * date：2018/4/26
 * time：下午4:36
 */
public class UserContext {
    public UserContext() {
    }
    public static SecurityUserDetails getUserDetails() {
        SecurityUserDetails userDetails = null;
        SecurityContext sc = SecurityContextHolder.getContext();
        Authentication ac = sc.getAuthentication();
        if (ac != null) {
            if (ac.getPrincipal().equals("anonymousUser")){
                userDetails = new SecurityUserDetails();
                userDetails.setUserId(0);
            }else{
                userDetails = (SecurityUserDetails)ac.getPrincipal();
            }
        }

        return userDetails;
    }

    public static Integer getUserID() {
        SecurityUserDetails userDetails = getUserDetails();
        if (userDetails != null) {
            return userDetails.getUserId();
        } else {
            throw new BuzException(BuzEnum.DATA_NOT_FOUND);
        }
    }

}
